﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using CompanyBussiness;

namespace Website.admin.Control
{
    public partial class cAccountManagement : System.Web.UI.UserControl
    {
        
        LanguagesManagement languageMana = new LanguagesManagement();
       
        CheckValid cv = new CheckValid();
        public int CurPage = 1;
        int TotalRow;
        int TotalPage;
        int StartRow = 0;
        int categoryIDs;
        string modulCode;
        AccountManagement accountMana = new AccountManagement();
        VwInternalUser vwInternal = new VwInternalUser();
        MD5 md5 = new MD5();
        string strLogDetail = "";
        CompanyBussiness.Account account = new Account();
        CompanyBussiness.AccountLog accountLog = new AccountLog();


        protected void Page_Load(object sender, EventArgs e)
        {
            fail.Visible = false;
            success.Visible = false;
            bindDropDownListFromDateTime(ddlFromHour, "h", false);
            bindDropDownListFromDateTime(ddlFromMinute, "m", false);
            BindDropDownListToDateTime(ddlToHour, "h", true);
            BindDropDownListToDateTime(ddlToMinute, "m", true);
            bdFromDate.SelectedDate = DateTime.Now;
            bdToDate.SelectedDate = DateTime.Now;

            if (!Page.IsPostBack)
            {
                ContentSearch();
            }
            
            
        }
        
        protected int GetRowinPage()
        {
            return int.Parse(dropRows.SelectedValue.ToString());
        }

        protected void LoadGridView(VwInternalUser vw, int take)
        {
            try
            {

                if (Request["Page"] == null)
                {
                    CurPage = 1;
                }
                else
                {
                    CurPage = Convert.ToInt32(Request["Page"]);
                }

                dropChoicePage.SelectedValue = CurPage.ToString();

                if (CurPage > 1)
                {
                    StartRow = (CurPage - 1) * 10;
                }
                else
                {
                    StartRow = 0;
                }


                GridViewList.DataSource = accountMana.GetAccountInternalSearch(vw, GetFromDate(), GetToDate(), take, StartRow);
                GridViewList.DataBind();
                TotalRow = accountMana.GetNumberInternalSearch(vw, GetFromDate(), GetToDate());
                
                

                if (TotalRow == 0)
                {
                    divpagination.Visible = false;
                    fail.Visible = true;
                    lbError.Text = "Không có tài khoản nào!";
                    return;
                }
                else
                {
                    pnPagination.Visible = true;
                    conditionsRight.Visible = true;
                    fail.Visible = false;
                    success.Visible = false;
                }

                this.Pagination(take);
            }
            catch (Exception)
            {

            }
        }

        protected void Pagination(int take)
        {
            try
            {
                if (TotalRow % take == 0)
                    TotalPage = TotalRow / take;
                else
                    TotalPage = (TotalRow / take) + 1;

                dropChoicePage.Items.Clear();
                for (int i = 0; i < TotalPage; i++)
                {
                    dropChoicePage.Items.Add((i + 1).ToString());
                }


                if (CurPage > 1)
                {
                    lnkFirst.NavigateUrl = Request.CurrentExecutionFilePath + "?" + CONST.ACTION + "=CreateCategory&" + CONST.QUERYSTRING_CATEGORY + "=" + categoryIDs + "&Page=" + Convert.ToString(1);
                    lnkPrev.NavigateUrl = Request.CurrentExecutionFilePath + "?" + CONST.ACTION + "=CreateCategory&" + CONST.QUERYSTRING_CATEGORY + "=" + categoryIDs + "&Page=" + Convert.ToString(CurPage - 1);
                }
                if (CurPage < TotalPage && CurPage > 1)
                {
                    lnkLast.NavigateUrl = Request.CurrentExecutionFilePath + "?" + CONST.ACTION + "=CreateCategory&" + CONST.QUERYSTRING_CATEGORY + "=" + categoryIDs + "&Page=" + Convert.ToString(TotalPage.ToString());
                    lnkNext.NavigateUrl = Request.CurrentExecutionFilePath + "?" + CONST.ACTION + "=CreateCategory&" + CONST.QUERYSTRING_CATEGORY + "=" + categoryIDs + "&Page=" + Convert.ToString(CurPage + 1);
                }


                numCurrent.NavigateUrl = Request.CurrentExecutionFilePath + "?" + CONST.ACTION + "=CreateCategory&" + CONST.QUERYSTRING_CATEGORY + "=" + categoryIDs + "&Page=" + Convert.ToString(CurPage);
                numBefore.NavigateUrl = Request.CurrentExecutionFilePath + "?" + CONST.ACTION + "=CreateCategory&" + CONST.QUERYSTRING_CATEGORY + "=" + categoryIDs + "&Page=" + Convert.ToString(CurPage - 1);
                numAfter.NavigateUrl = Request.CurrentExecutionFilePath + "?" + CONST.ACTION + "=CreateCategory&" + CONST.QUERYSTRING_CATEGORY + "=" + categoryIDs + "&Page=" + Convert.ToString(CurPage + 1);

                if (CurPage == 1 && TotalPage == 1)
                {
                    numCurrent.Text = CurPage.ToString();
                    numBefore.Text = "";
                    numAfter.Text = "";
                    numBefore.Visible = false;
                    numAfter.Visible = false;
                }
                else if (CurPage == 1 && TotalPage > 1)
                {
                    numCurrent.Text = CurPage.ToString();
                    numBefore.Text = "";
                    numBefore.Visible = false;
                    numAfter.Text = Convert.ToString(CurPage + 1);
                }
                else if (1 < CurPage && CurPage < TotalPage)
                {
                    numCurrent.Text = CurPage.ToString();
                    numBefore.Text = Convert.ToString(CurPage - 1);
                    numAfter.Text = Convert.ToString(CurPage + 1);
                }
                else if (CurPage == TotalPage)
                {
                    numCurrent.Text = CurPage.ToString();
                    numBefore.Text = Convert.ToString(CurPage - 1);
                    numAfter.Text = "";
                    numAfter.Visible = false;
                }
            }
            catch (Exception)
            {

            }
        }

        protected void btnActive_Command(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Active")
            {
                Session[CONST.SESSION_INTERNALUSER] = Convert.ToInt32(e.CommandArgument);
                try
                {
                    account = new Account();
                    account.AccountID = accountMana.GetAccountIDByInternalUserID((int)Session[CONST.SESSION_INTERNALUSER]);
                    accountMana.ActiveAccount(account);
                    ContentSearch();
                }
                catch (Exception)
                {

                }
            }
        }

        protected void btnUpdate_Command(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Update")
            {
                Session[CONST.SESSION_ACCOUNTID] = Convert.ToInt32(e.CommandArgument);
                try
                {
                    Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_NAME] = "UpdateAccount";
                    Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_TYPE] = "UpdateAccount";
                    Response.Redirect("Administrator.aspx?" + CONST.ACTION + "=UpdateAccount&" + CONST.QUERYSTRING_ACCOUNTID + "=" + Session[CONST.SESSION_ACCOUNTID] + "&Mod=" + "MACCOUNT");
                }
                catch (Exception)
                {

                }
            }
        }

        protected void btnPermission_Command(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Permission")
            {
                Session[CONST.SESSION_ACCOUNTID] = Convert.ToInt32(e.CommandArgument);
                try
                {
                    Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_NAME] = "AccountPermission";
                    Response.Redirect("Administrator.aspx?" + CONST.ACTION + "=AccountPermission&acc=" + Session[CONST.SESSION_ACCOUNTID].ToString());
                }
                catch (Exception)
                {

                }
            }
        }

        protected void ContentSearch()
        {
            
            string error = string.Empty;

            if (CheckValidDate(ref error))
            {
                vwInternal.UserName = txtUserName.Text;

                if (dropStatus.SelectedValue.ToString() == "0")
                {
                    vwInternal.Roles = false;
                }
                else if (dropStatus.SelectedValue.ToString() == "1")
                {
                    vwInternal.Roles = true;
                }

                this.LoadGridView(vwInternal, int.Parse(dropRows.SelectedValue.ToString()));
            }
            else
            {
                lbError.Text = error;
                fail.Visible = true;
                return;
            }
        }

        private static void bindDropDownListFromDateTime(DropDownList ddlControl, string option, bool getNow)
        {
            switch (option)
            {
                case "h":
                    {
                        var li1 = new ListItem("Giờ", string.Empty);
                        ddlControl.Items.Insert(0, li1);
                        for (int i = 0; i <= 23; i++)
                        {
                            var li = new ListItem(i.ToString(), i.ToString());
                            ddlControl.Items.Add(li);
                        }
                        if (getNow)
                        {
                            ddlControl.SelectedValue = DateTime.Now.Hour.ToString();
                        }
                        else
                        {
                            ddlControl.SelectedIndex = 1;
                        }
                        break;
                    }
                case "m":
                    {
                        var li1 = new ListItem("Phút", string.Empty);
                        ddlControl.Items.Insert(0, li1);
                        for (int i = 0; i <= 59; i++)
                        {
                            var li = new ListItem(i.ToString(), i.ToString());
                            ddlControl.Items.Add(li);
                        }
                        if (getNow)
                        {
                            ddlControl.SelectedValue = DateTime.Now.Minute.ToString();
                        }
                        else
                        {
                            ddlControl.SelectedIndex = 1;
                        }
                        break;
                    }
                default:
                    {
                        var li1 = new ListItem("Chọn", string.Empty);
                        ddlControl.Items.Insert(0, li1);
                        ddlControl.SelectedIndex = 0;
                        break;
                    }
            }
        }

        private static void BindDropDownListToDateTime(ListControl ddlControl, string option, bool getNow)
        {
            switch (option)
            {
                case "h":
                    {
                        var li1 = new ListItem("Giờ", string.Empty);
                        ddlControl.Items.Insert(0, li1);
                        for (int i = 0; i <= 23; i++)
                        {
                            var li = new ListItem(i.ToString(), i.ToString());
                            ddlControl.Items.Add(li);
                        }
                        if (getNow)
                        {
                            ddlControl.SelectedValue = DateTime.Now.Hour.ToString();
                        }
                        else
                        {
                            ddlControl.SelectedIndex = 0;
                        }
                        break;
                    }
                case "m":
                    {
                        var li1 = new ListItem("Phút", string.Empty);
                        ddlControl.Items.Insert(0, li1);
                        for (int i = 0; i <= 59; i++)
                        {
                            var li = new ListItem(i.ToString(), i.ToString());
                            ddlControl.Items.Add(li);
                        }
                        if (getNow)
                        {
                            ddlControl.SelectedValue = DateTime.Now.Minute.ToString();
                        }
                        else
                        {
                            ddlControl.SelectedIndex = 0;
                        }
                        break;
                    }
                default:
                    {
                        var li1 = new ListItem("Chọn", string.Empty);
                        ddlControl.Items.Insert(0, li1);
                        ddlControl.SelectedIndex = 0;
                        break;
                    }
            }
        }

        private DateTime GetFromDate()
        {
            string time = ddlFromHour.SelectedValue + ":" + ddlFromMinute.SelectedValue + ":00";
            string date = bdFromDate.SelectedDate.ToShortDateString();
            DateTime result = DateTime.Parse(date + " " + time);
            return result;
        }

        private DateTime GetToDate()
        {
            string time = ddlToHour.SelectedValue + ":" + ddlToMinute.SelectedValue + ":00";
            string date = bdToDate.SelectedDate.ToShortDateString();
            DateTime result = DateTime.Parse(date + " " + time);
            return result;
        }

        private bool CheckValidDate(ref string error)
        {
            error = string.Empty;
            if (ddlFromHour.SelectedValue == string.Empty)
            {
                error += "<li>Bạn chưa chọn giờ ngày bắt đầu</li>";
            }
            if (ddlFromMinute.SelectedValue == string.Empty)
            {
                error += "<li>Bạn chưa chọn phút cho ngày bắt đầu</li>";
            }
            if (ddlToHour.SelectedValue == string.Empty)
            {
                error += "<li>Bạn chưa chọn giờ ngày kết thúc</li>";
            }
            if (ddlToMinute.SelectedValue == string.Empty)
            {
                error += "<li>Bạn chưa chọn phút cho ngày kết thúc</li>";
            }
            if (bdFromDate.SelectedValue == null)
            {
                error += "<li>Bạn chưa chọn ngày bắt đầu</li>";
            }
            if (bdToDate.SelectedValue == null)
            {
                error += "<li>Bạn chưa chọn ngày kết thúc</li>";
            }
            if (!error.Equals(string.Empty))
            {
                return false;
            }
            DateTime fromDate = GetFromDate();
            DateTime toDate = GetToDate();

            if (fromDate > toDate)
            {
                error = "Khoảng thời gian bạn chọn không hợp lệ";
                return false;
            }
            return true;
        }


        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                ContentSearch();
            }
            catch (Exception ex)
            { 
            
            }
        }

        protected void GridViewList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                VwInternalUser obj = (VwInternalUser)e.Row.DataItem;

                LinkButton btnActive = (LinkButton)e.Row.FindControl("btnActive");
                if (obj.AccountStatus == false)
                {
                    btnActive.Text = "Không hoạt động";
                }
                else
                {
                    btnActive.Text = "Hoạt động";
                    btnActive.Enabled = false;
                }
                    
            }
            else
                return;
        }

        protected void btnCreateNew_Click(object sender, EventArgs e)
        {
            Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_NAME] = "CreateAccount";
            Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_TYPE] = "AddNews";
            Response.Redirect("Administrator.aspx?" + CONST.ACTION + "=CreateAccount&Mod=" + "MACCOUNT");
        }

        protected void dropChoicePage_SelectedIndexChanged(object sender, EventArgs e)
        {
            CurPage = Convert.ToInt32(dropChoicePage.SelectedValue.ToString());
            Response.Redirect(Request.CurrentExecutionFilePath + "?" + CONST.ACTION + "=AccountMana&" + CONST.QUERYSTRING_CATEGORY + "=" + categoryIDs + "&Page=" + Convert.ToString(CurPage) + "&Mod=MACCOUNT");
        }

        protected void dropRows_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ContentSearch();
            }
            catch (Exception)
            {

            }
        }
    }
}